#!/usr/bin/env python
# -*- coding: UTF-8 -*-

"""
不想写
"""

import time
import os.path

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
import tornado.gen

from tornado.options import define, options
define("port", default=8000, help="run service on the given port", type=int)

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", IndexHandler),
            (r"/verify", VerifyHandler) 
        ]
        settings = dict(
            template_path = os.path.join(os.path.dirname(__file__), "templates"),
            static_path = os.path.join(os.path.dirname(__file__), "static"),
            xsrf_cookies = True,
            debug = True,
        )
        tornado.web.Application.__init__(self, handlers, **settings)

class BaseHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    @tornado.gen.engine
    def verify_apache_dos(self, url):
        http_headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36",
            "Request-Range": "bytes=5-0,1-1,2-2,3-3,4-4,5-5,6-6,7-7,8-8,9-9,10-10",
            "Range": "bytes=5-0,1-1,2-2,3-3,4-4,5-5,6-6,7-7,8-8,9-9,10-10"
        }
        http_client = tornado.httpclient.AsyncHTTPClient()
        http_url = url
        http_request = tornado.httpclient.HTTPRequest(
            url=http_url, 
            method="HEAD",
            headers=http_headers,
            connect_timeout=5,
            request_timeout=10
        )
        http_response = yield tornado.gen.Task(http_client.fetch, http_request)
        self.set_header("Content-Type", "application/json; charset=utf-8")
        if http_response.code == 206 and http_response.headers.has_key("Accept-Ranges"):
            self.write('{"error":"", "data":"ok"}')
            self.finish()
            return 
        else:
            self.write('{"error":"", "data":"no"}')
        self.finish()

class IndexHandler(BaseHandler):
    def get(self):
        self.render("index.html", page_title="常规安全漏洞在线测试系统")

class VerifyHandler(BaseHandler):
    def get(self):
        url = self.get_argument("url")
        service = self.get_argument("service")
        self.verify_apache_dos(url)

if __name__ == "__main__":
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()